package com.ysstech.common.exception;



import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ysstech.common.util.resultutil.RestResult;
import com.ysstech.common.util.resultutil.ResultCode;
import com.ysstech.common.util.resultutil.ResultGenerator;
import dm.jdbc.driver.DMException;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 异常通用处理
 */
@Slf4j
@ControllerAdvice
public class DefaultExceptionAdvice {

    /**
     * 所有异常统一处理
     * 返回状态码:500
     */
    @ResponseBody
    @ExceptionHandler({Exception.class})
    public RestResult exception(Exception ex, HttpServletRequest request, HttpServletResponse response) {
        try {
            log.error("请求地址：" + request.getRequestURL());
            log.error("错误信息：" + ex.getMessage());
            //异常事物回滚
            //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            if (null == ex) {
                return ResultGenerator.getFreeResult(ResultCode.REQUEST_NOT_FOUND, "未知异常!");
            }
            // service层抛出的异常包装了EXception
            if (ex.getCause() instanceof BusinessException) {
                return ResultGenerator.getBusinessResult(ex.getCause().getMessage());
            }
            if (ex instanceof BusinessException) {
                return ResultGenerator.getBusinessResult(ex.getMessage());
            }
            if (ex instanceof UnauthorizedException) { // 权限异常
                return ResultGenerator.getFreeResult(ResultCode.UNAUTHORIZED, "你没有该页面的权限，请联系管理员！");
            }
            if(ex instanceof DMException){
                return ResultGenerator.getBusinessResult(ex.getMessage());
            }
        } catch (Exception e) {
            log.error(e.toString());
            return ResultGenerator.getFreeResult(ResultCode.REQUEST_NOT_FOUND, "系统异常，请联系管理员!"); //其它异常直接返回到前台默认的code 400
        }
        return ResultGenerator.getFreeResult(ResultCode.REQUEST_NOT_FOUND, "系统异常，请联系管理员!"); //其它异常直接返回到前台默认的code 400
    }

}
